﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using TfsBranchLib2.Model;
using TfsComLib.TfsBranchLib2;

namespace TfsBranchLib2.View
{
    /// <summary>
    ///     Interaction logic for BranchListBox.xaml
    ///     United Component to select a list of branches
    /// </summary>
    public partial class BranchListBox : UserControl
    {
        private BranchedHistoryContext branchedHistoryContext;

        private readonly CollectionViewSource branchView = new CollectionViewSource();

        public BranchListBox()
        {
            InitializeComponent();
            //branchView.
            branchListView.SetBinding(ItemsControl.ItemsSourceProperty, new Binding {Source = branchView});
            // Show only selected items
            branchView.Filter += (source, eventArg) =>
            {
                var anItem = eventArg.Item as BranchData;
                if (anItem == null)
                {
                    eventArg.Accepted = false;
                    return;
                }
                eventArg.Accepted = anItem.IsSelected;
            };
        }

        internal void SetBindings(BranchedHistoryContext branchedHistoryContext)
        {
            this.branchedHistoryContext = branchedHistoryContext;

            // Binding this.branchView.Source = branchedHistoryContext.SelectedBranchesCache.Branches;
            BindingOperations.SetBinding(branchView, CollectionViewSource.SourceProperty,
                new Binding("SelectedBranchesCache.Branches") {Source = branchedHistoryContext});

            branchView.View.Refresh();

            branchedHistoryContext.SelectedBranchesCache.OnRefresh += SelectedBranchesCache_OnRefresh;
        }

        private void SelectedBranchesCache_OnRefresh(object sender, EventArgs e)
        {
            branchView.View.Refresh();
        }

        private void EditBranchList(object sender, RoutedEventArgs e)
        {
            var branchListEditPopup = new BranchListEditPopup(branchedHistoryContext);
            branchListEditPopup.ShowDialog();
        }

        private void SelectBranchSet(object sender, RoutedEventArgs e)
        {
            branchedHistoryContext.CheckLoaded();
            var recentBranchSetPopup = new RecentBranchSetPopup(branchedHistoryContext);
            recentBranchSetPopup.ShowDialog();
        }
    }
}